﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace D.WebApi.Core.Filters
{
    /// <summary>
    /// Action执行前后拦截
    /// 应用场景：记录日志
    /// 使用方式：
    /// 在Action方法上面加上：[TypeFilter(typeof(ActionFilterAttribute))] 
    /// 或者：[ServiceFilter(typeof(ActionFilterAttribute))]
    /// </summary>
    public class ExtActionFilterAttribute : Attribute, IActionFilter
    {
        private readonly ILogger _logger;

        public ExtActionFilterAttribute(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<ExtActionFilterAttribute>();
        }


        /// <summary>
        /// 进入Action前
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var para = context.HttpContext.Request.QueryString.Value;
            var controllerName = context.HttpContext.GetRouteValue("controller");
            var actionName = context.HttpContext.GetRouteValue("action");

            _logger.LogDebug($"开始执行{controllerName}控制器中{actionName}方法，参数为:{para}");
        }


        /// <summary>
        /// Action执行完成后
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            var result = JsonConvert.SerializeObject(context.Result);
            var controllerName = context.HttpContext.GetRouteValue("controller");
            var actionName = context.HttpContext.GetRouteValue("action");

            _logger.LogDebug($"返回{controllerName}控制器中{actionName}方法，结果为:{result}");
        }

    }
}
